import { makeAutoObservable, } from "mobx";
import { showError, showLoading, showSuccess } from "../components/Message";
import { ActivateSubscribeService, CancelSubscribeService, PayData, SubscribeItem, SubscribeListService, SubscribeService } from "../services/SubscribeService";

class SubscribeStore {
    public list: Array<SubscribeItem> = [];
    public loading: boolean = false;
    public showVideoItem: string = '';
    public showConfirm: boolean = false;
    public confirmLoading: boolean = false;
    public activateLoading: boolean = false;
    public subscribeLoadingId?: string ;
    public showPay: boolean = false;
    public payData?:PayData;

    constructor() {
        makeAutoObservable(this);
    }

    public async getData(showLoading: boolean = true) {
        if (this.loading) {
            return;
        }
        let response: Array<SubscribeItem>;
        if (showLoading)
            this.loading = true;
        try {
            response = await new SubscribeListService().send();
        } catch (e:any) {
            this.loading = false;
            showError(e);
            return;
        }
        this.loading = false;
        this.list = response;
    }

    public async activateSubscribe(id: string) {
        if (this.activateLoading) {
            return;
        }
        this.activateLoading = true;
        showLoading('激活中...');
        try {
            await new ActivateSubscribeService(id).send();
            await this.getData(false);
        } catch (e:any) {
            showError(e);
            this.activateLoading = false;
            return;
        }
        this.activateLoading = false;
        this.showConfirm = false;
        showSuccess('激活成功！');
    }

    public async subscribe(id: string) {
        if (this.subscribeLoadingId === id) {
            return;
        }
        this.subscribeLoadingId = id;
        try {
            this.payData = await new SubscribeService(id).send();
            await this.getData(false);
        } catch (e:any) {
            showError(e);
            this.subscribeLoadingId = undefined;
            return;
        }
        this.subscribeLoadingId = undefined;
        window.open(this.payData.url,'_blank');
    }

    public async cancelSubscribe() {
        this.confirmLoading = true;
        try {
            await new CancelSubscribeService().send();
            await this.getData(false);
        } catch (e:any) {
            showError(e);
            this.confirmLoading = false;
            return;
        }
        this.confirmLoading = false;
        this.showConfirm = false;
        showSuccess('取消成功！');
    }

}

const subscribeStore = new SubscribeStore();

export { subscribeStore };